package com.paas.demo.netty;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.ReferenceCountUtil;

public class TCPServerHandler extends ChannelInboundHandlerAdapter { // (1)

	private final Logger logger = LoggerFactory.getLogger(getClass());
	
	private final SessionManager sessionManager;

	
	public TCPServerHandler() {
		this.sessionManager = SessionManager.getInstance();
		
		System.out.println("####### new TCPServerHandler #######");
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { // (2)
		try {
			
			ByteBuf buf = (ByteBuf) msg;

			if (buf.readableBytes() <= 0) {
				// ReferenceCountUtil.safeRelease(msg);
				return;
			}
			byte[] bs = new byte[buf.readableBytes()];
			buf.readBytes(bs);
			
			String originMsg = new String(bs);
			logger.info("receive msg : " + originMsg);

			
		}catch(Exception e){
			//异常不做处理
			logger.error("channelRead msg errir .", e);
		} 
		finally {
			release(msg);
		}
	}



	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // (4)
		logger.error("发生异常:{}", cause.getMessage());
		cause.printStackTrace();
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		logger.info("终端连接:{}", ctx.channel());
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		final String sessionId = ctx.channel().id().asLongText();
		Session session = sessionManager.findBySessionId(sessionId);
		if (session == null) {
			logger.info("终端断开连接:{}", ctx.channel());
			ctx.channel().close();
			return;
		}
		this.sessionManager.removeBySessionId(sessionId);
		logger.info("终端断开连接:{}", session);
		ctx.channel().close();
		// ctx.close();
	}

	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
		if (IdleStateEvent.class.isAssignableFrom(evt.getClass())) {
			IdleStateEvent event = (IdleStateEvent) evt;
			if (event.state() == IdleState.READER_IDLE) {
				logger.info("服务器主动断开连接:{}", ctx.channel());
				ctx.close();
			}
		}
	}

	private void release(Object msg) {
		try {
			ReferenceCountUtil.release(msg);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}